package cn.controlsys.service.impl;

import cn.controlsys.common.saiheyi.SaiheyiConstants;
import cn.controlsys.controller.SaiheyiController;
import cn.controlsys.dao.PaymentRecordMapper;
import cn.controlsys.dao.RechargeAccountMapper;
import cn.controlsys.model.PaymentRecord;
import cn.controlsys.model.RechargeAccount;
import cn.controlsys.operationDao.HouseResourceMapper;
import cn.controlsys.pojo.OrderStatusVO;
import cn.controlsys.pojo.WecbillQueryVO;
import cn.controlsys.pojo.WecbilldataVO;
import cn.controlsys.pojo.WecbillpostVO;
import cn.controlsys.service.SaiheyiService;
import cn.controlsys.service.TimedTaskService;
import cn.controlsys.utils.DateUtils;
import cn.controlsys.utils.HttpClientResult;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @Description: Created by Administrator on 2018/12/24.
 */
@Service
public class TimedTaskServiceImpl implements TimedTaskService {
    private static Logger logger = LoggerFactory.getLogger(TimedTaskServiceImpl.class);
    @Autowired
    RechargeAccountMapper rechargeAccountMapper;
    @Autowired
    PaymentRecordMapper paymentRecordMapper;
    @Autowired
    SaiheyiService saiheyiService;
    @Autowired
    HouseResourceMapper houseResourceMapper;


    @Scheduled(cron = SaiheyiConstants.WEC_BILL_POST_CRON)
    @Override
    public void wecbillpostCron() {
        logger.info("查询提交定时开始");
        //获取户号信息
        List<RechargeAccount> rechargeAccountList = rechargeAccountMapper.selectRechargeAccount();
        if (CollectionUtils.isEmpty(rechargeAccountList)) {
            logger.info("查询提交定时结束:本次定时户号需要查询");
            return;
        }
        String ymonth = DateUtils.getCurrentYmonthStr();
        for (RechargeAccount rechargeAccount : rechargeAccountList) {
            try {
                //查看户号运营状态：
                Byte operationStatus = houseResourceMapper.getHouseOperationStatusByAccount(rechargeAccount.getWecAccount());
                if (operationStatus != 0) {
                    continue;//不是正在运营的不用缴费
                }
                HttpClientResult httpClientResult = saiheyiService.wecbillpost(rechargeAccount.getProductId(), rechargeAccount.getWecAccount(), ymonth);
                if (httpClientResult != null && httpClientResult.getCode() == 200) {
                        WecbillpostVO wecbillpostVO = JSONObject.parseObject(httpClientResult.getContent(), WecbillpostVO.class);
                        if ("true".equals(wecbillpostVO.getStatus())) {
                            String stockordernumber = wecbillpostVO.getContent().getStockordernumber();
                            PaymentRecord paymentRecord = new PaymentRecord();
                            paymentRecord.setQueryOrderNumber(stockordernumber);
                            paymentRecord.setQueryTime(new Date());
                            paymentRecord.setStatus((byte) 1);
                            paymentRecord.setWecAccount(rechargeAccount.getWecAccount());
                            paymentRecord.setWecType(rechargeAccount.getWecType());
                            paymentRecord.setBillDate(ymonth);
                            paymentRecord.setDescription("待出账单");
                            paymentRecordMapper.insertSelective(paymentRecord);
                        }
                }else {
                    logger.error("[户号提交账单查询接口失败]，户号：{},类型：{}",rechargeAccount.getWecAccount(),rechargeAccount.getWecType());
                }
            } catch (Exception e) {
                logger.error("[户号提交账单查询异常]，户号：{},类型：{}",rechargeAccount.getWecAccount(),rechargeAccount.getWecType());
                e.printStackTrace();
            }
        }
        logger.info("查询提交定时结束");
    }


    @Override
    @Scheduled(cron = SaiheyiConstants.WEC_BILL_QUERY_CRON)
    public void wecbillqueryCron() {
        logger.info("查询定时开始");
        //获取待查账信息
        List<PaymentRecord> queryOrderNumberList = paymentRecordMapper.selectWecBillQueryList();
        if (CollectionUtils.isEmpty(queryOrderNumberList)) {
            logger.info("查询定时结束:本次定时没有账单查询");
            return;
        }
        for (PaymentRecord paymentRecord : queryOrderNumberList) {
            try {
                HttpClientResult httpClientResult = saiheyiService.wecbillquery(paymentRecord.getQueryOrderNumber());
                if (httpClientResult != null && httpClientResult.getCode() == 200) {
                    WecbillQueryVO wecbillQueryVO = JSONObject.parseObject(httpClientResult.getContent(), WecbillQueryVO.class);
                    if ("true".equals(wecbillQueryVO.getStatus())) {
                        List<WecbilldataVO> wecbilldataVOList = wecbillQueryVO.getContent().getWecbilldata();
                        String billAmount = "0";
                        String delayfee = "0";
                        if (!CollectionUtils.isEmpty(wecbilldataVOList)) {
                            billAmount = wecbilldataVOList.get(0).getBillamount() == null ? "0" : wecbilldataVOList.get(0).getBillamount();
                            delayfee = wecbilldataVOList.get(0).getDelayfee() == null ? "0" : wecbilldataVOList.get(0).getDelayfee();
                        }
                        Byte ststus = 2;
                        String description = "待缴费";
                        if (new BigDecimal(delayfee).compareTo(BigDecimal.ZERO) == 0 && new BigDecimal(billAmount).compareTo(BigDecimal.ZERO) == 0) {
                            ststus = 6;//滞纳金和账单金额小于0不用缴费
                            description = "滞纳金和账单金额小于0不用缴费";
                        }
                        //查看户号运营状态：
                        Byte operationStatus = houseResourceMapper.getHouseOperationStatusByAccount(paymentRecord.getWecAccount());
                        if (operationStatus != 0) {
                            ststus = 6;//不是正在运营的不用缴费
                            description = "不再运营的不用缴费";
                        }
                        paymentRecord.setLateFee(new BigDecimal(delayfee));
                        paymentRecord.setQueryFinishTime(new Date());
                        paymentRecord.setStatus(ststus);
                        paymentRecord.setBillMoney(new BigDecimal(billAmount));
                        paymentRecord.setDescription(description);
                        paymentRecordMapper.updateByPrimaryKeySelective(paymentRecord);
                    }
                }else {
                    paymentRecord.setStatus((byte)7);
                    paymentRecord.setDescription("账单查询接口失败");
                    paymentRecordMapper.updateByPrimaryKeySelective(paymentRecord);
                }
            } catch (Exception e) {
                logger.error("[账单查询失败]，商户订单号",paymentRecord.getQueryOrderNumber());
                e.printStackTrace();
            }
        }
        logger.info("查询定时结束");
    }


    @Override
    @Scheduled(cron = SaiheyiConstants.WEC_RECHARGE_CRON)
    public void wrechargeCron() {
        logger.info("缴费定时开始");
        //获取待查账信息
        List<PaymentRecord> rechargePaymentRecordList = paymentRecordMapper.selectWecBillRechargeList();
        if (CollectionUtils.isEmpty(rechargePaymentRecordList)) {
            logger.info("缴费定时结束:本次定时没有户号需要缴费");
            return;
        }
        for (PaymentRecord paymentRecord : rechargePaymentRecordList) {
            try {
                List<RechargeAccount> rechargeAccountList = rechargeAccountMapper.selectRechargeAccountByWecAccount(paymentRecord.getWecAccount(), paymentRecord.getWecType());
                if (CollectionUtils.isEmpty(rechargeAccountList)) {
                    continue;
                }
                String productId = rechargeAccountList.get(0).getProductId();
                HttpClientResult httpClientResult = saiheyiService.wrecharge(productId, paymentRecord.getLateFee() + "",
                        paymentRecord.getWecAccount(), paymentRecord.getBillMoney() + "");
                if (httpClientResult != null && httpClientResult.getCode() == 200) {
                    WecbillpostVO wecbillpostVO = JSONObject.parseObject(httpClientResult.getContent(), WecbillpostVO.class);
                    Byte status = 5;
                    if ("true".equals(wecbillpostVO.getStatus())) {
                        paymentRecord.setRechargeOrderNumber(wecbillpostVO.getContent().getStockordernumber());
                        status = 3;
                    }
                    paymentRecord.setStatus(status);
                    paymentRecord.setRechageTime(new Date());
                    paymentRecord.setDescription("[缴费]:"+wecbillpostVO.getMessage());
                    paymentRecordMapper.updateByPrimaryKeySelective(paymentRecord);
                }else {
                    paymentRecord.setStatus((byte) 7);
                    paymentRecord.setDescription("缴费接口失败");
                    paymentRecordMapper.updateByPrimaryKeySelective(paymentRecord);
                }
            } catch (Exception e) {
                logger.error("[缴费异常]，商户订单号",paymentRecord.getRechargeOrderNumber());
                e.printStackTrace();
            }
        }
        logger.info("缴费定时结束");
    }


    @Override
    @Scheduled(cron = SaiheyiConstants.ORDER_STATUS_CRON)
    public void orderStatus() {
        logger.info("查询缴费定时开始");
        //获取已缴费信息
        List<PaymentRecord> orderStatusPaymentRecordList = paymentRecordMapper.selectOrderStatusList();
        if (CollectionUtils.isEmpty(orderStatusPaymentRecordList)) {
            logger.info("查询缴费定时结束:本次定时没有户号需要查询");
            return;
        }
        for (PaymentRecord paymentRecord : orderStatusPaymentRecordList) {
            try {
                if (StringUtils.isBlank(paymentRecord.getRechargeOrderNumber())) {
                    paymentRecord.setStatus((byte) 5);
                    paymentRecord.setDescription("没有缴费");
                    paymentRecordMapper.updateByPrimaryKeySelective(paymentRecord);
                    continue;
                }
                HttpClientResult httpClientResult = saiheyiService.orderStatus(paymentRecord.getRechargeOrderNumber());
                if (httpClientResult != null && httpClientResult.getCode() == 200) {
                    OrderStatusVO orderStatusVO = JSONObject.parseObject(httpClientResult.getContent(), OrderStatusVO.class);
                    if ("true".equals(orderStatusVO.getStatus())) {
                        String payStatus = orderStatusVO.getContent().getPaystatus();
                        if ("4".equals(payStatus)) {//成功
                            paymentRecord.setStatus((byte) 4);
                            paymentRecordMapper.updateByPrimaryKeySelective(paymentRecord);
                            List<RechargeAccount> rechargeAccountList = rechargeAccountMapper.selectRechargeAccountByWecAccount(paymentRecord.getWecAccount(), paymentRecord.getWecType());
                            if (!CollectionUtils.isEmpty(rechargeAccountList)) {
                                RechargeAccount rechargeAccount = rechargeAccountList.get(0);
                                rechargeAccount.setLatestRechargeTime(new Date());
                                rechargeAccountMapper.updateByPrimaryKeySelective(rechargeAccount);
                            }
                        } else if ("5".equals(payStatus)) {//失败
                            String payresult = orderStatusVO.getContent().getPayresult() == null ? "" : orderStatusVO.getContent().getPayresult();
                            paymentRecord.setStatus((byte) 5);
                            paymentRecord.setDescription(payresult);
                            paymentRecordMapper.updateByPrimaryKeySelective(paymentRecord);
                        }
                    }
                } else {
                    paymentRecord.setStatus((byte)7);
                    paymentRecord.setDescription("缴费查询接口失败");
                    paymentRecordMapper.updateByPrimaryKeySelective(paymentRecord);
                }
            } catch (Exception e) {
                logger.error("[缴费查询异常]，商户订单号",paymentRecord.getRechargeOrderNumber());
                e.printStackTrace();
            }
        }
    }

}
